<template>
  <div>
    <base-modal
      :title="$t('task.setting.taskTypeSetting.manage.industryNames.name7')"
      :show.sync="visible"
      width="480px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <div class="service-dialog">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          
          label-position="top"
        >
          <el-form-item :label="$t('common.label.taskNo')" prop="taskNo">
            <div class="service-form-item">
              <el-input
                v-model="form.taskNo"
                :placeholder="$t('order.placeHolder.enterTaskNo')"
                style="width: 75%"
              ></el-input>
              <el-button class="add-task" @click="handleAddTask"
                >{{$t('common.base.create')}}</el-button
              >
            </div>
          </el-form-item>
        </el-form>
        <!-- <div class="service-form-tip">
          新建工单时，若客户未在“客户管理”列表中，将自动保存此客户信息录入系统
        </div> -->
        <div class="service-task">
          <div v-if="orderCorrelationServiceList.length">
            {{$t('order.component.associatedServices', {data1: orderCorrelationServiceList.length})}}
          </div>
          <div v-for="item in orderCorrelationServiceList" :key="item.taskId">
            {{ item.templateName }}
            <span @click="handleJumpTaskDetail(item.taskId)">{{
              item.taskNo
            }}</span>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading"
          >{{$t('common.base.makeSure')}}</el-button
        >
      </div>
    </base-modal>
  </div>
</template>

<script>
import { myService, saveTask, getLinkManId } from '@src/api/PortalApi.ts';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';

export default {
  emits: ['reloadPage'],
  data() {
    return {
      visible: false,
      loading: false,
      form: {
        taskNo: '',
      },
      rules: {
        taskNo: [
          { required: true, message: this.$t('order.placeHolder.enterTaskNo'), trigger: 'blur' },
        ],
      },
      orderCorrelationServiceList: [],
      orderId: '',
      phone: '',
      linkManId: '',
      customerId: '',
    };
  },
  methods: {
    open(id, phone) {
      this.visible = true;
      this.orderId = id;
      this.phone = phone;

      this.handleGetTaskList();
      this.getLinkManId();
    },
    handleAddTask() {
      let fromId = window.frameElement.getAttribute('id');
      if (this.linkManId) {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCreateTaskFromCustomer,
          key: this.customerId,
          titleKey: this.$t('common.pageTitle.pageCreateTask'),
          params: `bizId=${this.orderId}&bizType=serviceShop&linkmanId=${this.linkManId}`,
          fromId,
        });
      } else {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCreateTask,
          titleKey: this.$t('common.pageTitle.pageCreateTask'),
          params: `bizId=${this.orderId}&bizType=serviceShop`,
          fromId,
        });
      }

      this.handleClose();
    },
    async getLinkManId() {
      try {
        this.orderCorrelationServiceList = [];
        const { code, data } = await getLinkManId({ phone: this.phone });

        if (code !== '200' || !data) return;

        const { id, customerId } = data;

        this.linkManId = id || '';
        this.customerId = customerId || '';
      } catch (error) {
        console.error('getLinkManId error', error);
      }
    },
    async handleGetTaskList() {
      try {
        this.orderCorrelationServiceList = [];
        const { code, data } = await myService({ orderId: this.orderId });

        if (code !== '200' || !data) {
          return this.$message.error(this.$t('order.tips.relatedServiceFailed'));
        }

        this.orderCorrelationServiceList = data;
      } catch (error) {
        console.error('get order correlation service list error', error);
      }
    },
    // 跳转到工单详情
    handleJumpTaskDetail(id) {
      if (!id) return;

      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        fromId,
        type:PageRoutesTypeEnum.PageTaskView,
        key:id,
      });
    },
    handleClose() {
      this.visible = false;
      this.form = this.$options.data.call(this).form;
      this.$refs.formRef.clearValidate();
    },
    handleConfirm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {
            this.loading = true;
            const { code, msg } = await saveTask({
              orderId: this.orderId,
              taskNo: this.form.taskNo,
            });

            if (code !== '200') {
              this.loading = false;
              return this.$message.error(msg || this.$t('order.tips.associateOrderFailed'));
            }

            this.$message.success(this.$t('order.tips.associateOrderSuccess'));
            this.loading = false;
            this.handleClose();
            this.$emit('reloadPage');
          } catch (error) {
            this.loading = false;
            console.error('order correlation service error', error);
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.service-form-item {
  display: flex;
  align-items: center;

  .add-task {
    background: #f5f8fa;
    margin-left: 10px;
  }
}

.service-form-tip {
  color: #8c8c8c;
  font-size: 12px;
  margin-bottom: 16px;
}

.service-task {
  div {
    margin-bottom: 8px;
    color: #595959;
    font-size: 14px;
  }

  div:last-child {
    margin: 0;
  }

  span {
    color: $color-primary-light-6;
    cursor: pointer;
  }
}

.service-dialog {
  padding: 30px;
}
</style>
